<?php
// include the global config file
require_once("config.php");

// external lib: Opauth lib for authentication
require_once("lib/Opauth/Opauth.php");

// application internal classes
require_once("class/cache.class.php");
require_once("class/database.class.php");
require_once("class/blog.class.php");
require_once("class/user.class.php");
require_once("class/crypto.class.php");

// instanciate the blog
$b = new blog($_SERVER["HTTP_HOST"]);
$u = $b->getUser();
$httpHostVar = str_replace(".", "_", $_SERVER["HTTP_HOST"]);

/* define the sso user name */
$ssoExtId = "";

/* this script provides single sign-on across all domains */
if(array_key_exists("key", $_GET)){
	// check if the authkey requests logout
	if($_GET["key"]=="logout"){
		// perform the logout for sso as well
		$u->deleteAuthCookie();
	}else{
		// decode the auth key to its base64 value
		$authKey = str_replace(" ", "+", $_GET["key"]);

		/* check whether the cookie already exists */
		if($u->hasAuthCookie()){
			// check if the auth key user extid 
			// matches the user extid from the cookie
			// and if not, the auth key overwrites
			$u->verifyAuthCookie();
			$ssoExtId = $u->getExtId();

			// now verify the key and check the id
			$u->verifyAuthKey($authKey);
			if($u->getExtId()!=$ssoExtId){
				// we need to overwrite the auth cookie
				$u->setAuthCookie();
				$ssoExtId = $u->getExtId();
			}
		}else{
			// get the user object to check the auth key
			// and pass the data to the frontend
			$u = $b->getUser();
			$u->verifyAuthKey($authKey);

			// set the auth cookie
			$u->setAuthCookie();

			// set the extid of the sso
			// authenticated user
			$ssoExtId = $u->getExtId();
		}
	}
}

// set the javascript content type header
header("Content-Type: application/javascript");
print("var ".$httpHostVar."_userextid = '".$ssoExtId."';");
?>